import { computed, defineComponent, inject, ref } from "vue"
import "./editorStyle.scss"
import EditorBlocks from "./editor-blocks.jsx"
import EditorProps from "./editor-props.jsx"
import useMenu from "./js/useMenu.js"
import useItemFocus from "./js/useItemFocus.js"
import useItemMove from "./js/useItemMove.js"
import deepcopy from "deepcopy"

export default defineComponent({
	props: {
		modelValue: Object, // 确保类型匹配
	},
	emits: ["update:modelValue"],
	setup(props, ctx) {
		const config = inject("config")
		const data = computed({
			get() {
				return props.modelValue
			},
			set(value) {
				ctx.emit("update:modelValue", deepcopy(value))
			},
		})
		// console.log(123, JSON.stringify(data.value))

		let containerRef = ref(null)
		
		//左侧操作栏拖拽
		const { dragStart, drageEnd } = useMenu(data, containerRef)

		
		//点击焦点操作
		const { mousedown, clearAllFocus ,focusItem,lastFocusItem} = useItemFocus(data,(e)=>{

			// console.log(789,lastFocusItem);
			//聚焦拖拽操作
			const {mousedownAfter} = useItemMove(focusItem)
			mousedownAfter(e)
		})

		//自定义改变值
		const changeItem = (newItem)=>{
			// console.log(123,newItem,234,focusItem);
			let forcusArr = focusItem.value.focusArr
			if(forcusArr && forcusArr.length>0){
				//focusArr移除最后一项lastFocus
				forcusArr.pop()
			}
			data.value['blocks'] = [...focusItem.value.unFocusArr,...forcusArr,newItem]
		}

		const containerStyles = computed(() => ({
			width: data.value.container.width + "px",
			height: data.value.container.height + "px",
		}))
		return () => (
			<div className="editor">
				<div className="editor-left">
					{config.componentList.map((item) => (
						<div className="editor-left-item" draggable ondragstart={(e) => dragStart(e, item)} ondragend={drageEnd}>
							<div className="editor-left-item-label">{item.label}</div>
							<div className="editor-left-item-content">{item.preview()}</div>
						</div>
					))}
				</div>

				<div className="editor-center">
					<div className="editor-center-top">菜单栏</div>
					<div className="editor-center-content">
						<div style={containerStyles.value} className="editor-center-content-innner" onMousedown={clearAllFocus} ref={containerRef}>
							{data.value.blocks.map((item) => (
								<EditorBlocks onMousedown={(e) => mousedown(e, item)} item={item} style={item.focus ? { border: "1px dashed #ff0000" } : ""} />
							))}
						</div>
					</div>
				</div>
				<div className="editor-right">
					<EditorProps item={lastFocusItem} modelValue={data} onChangeItem={changeItem} />
				</div>
			</div>
		)
	},
})
